package com.edu.controller.user;

import com.edu.dto.ResultDto;
import com.edu.entity.UserEntity;
import com.edu.service.UserService;
import com.edu.service.impl.UserServiceImpl;
import com.edu.utils.ReturnCode;
import com.edu.utils.ServletHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;

/**
 * 用户注册控制器。
 * 该类继承自HttpServlet，处理来自客户端的用户注册请求。
 */
@WebServlet(urlPatterns = "/users/register")
public class RegisterController extends HttpServlet {
    UserService userService;

    /**
     * 初始化方法。
     * 在Servlet生命周期中被调用，用于初始化userService实例。
     */
    public void init() {
        userService = new UserServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        UserEntity user = ServletHelper.getRequestBodyAsObject(request, UserEntity.class);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        System.out.println(user.getUsername() + user.getEmail() + user.getPassword());
        boolean success = new UserServiceImpl().register(user.getUsername(), user.getEmail(), user.getPassword());

        if (success) {
            String rst = ResultDto.success(null);
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(rst);
        } else {
            String rst = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "注册失败。用户名可能已被使用。");
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(rst);
        }
    }
}
